#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <unistd.h>
#include <string>
#include <poll.h>
#include "log_pro.hpp"

class Socket
{
public:
    Socket()
    {
        init();
    }
    void init()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd == -1)
        {
            lg(FATAL, "socket create fail ! errno:%d %s", errno, strerror(errno));
            std::cout << errno << ": " << strerror(errno) << std::endl;
            exit(-1);
        }
    }

    void Bind(uint16_t port)
    {
        sockaddr_in server;
        server.sin_addr.s_addr = htonl(INADDR_ANY);
        // server.sin_addr.s_addr=inet_addr("0.0.0.0");
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        if (bind(_sockfd, (sockaddr *)&server, sizeof(server)) == -1)
        {
            lg(FATAL, "bind fail ! errno:%d %s", errno, strerror(errno));
            std::cout << errno << ": " << strerror(errno) << std::endl;
            exit(-1);
        }
    }

    void Listen()
    {
        if (listen(_sockfd, 10) == -1)
        {
            lg(FATAL, "listen fail ! errno:%d %s", errno, strerror(errno));
            std::cout << errno << ": " << strerror(errno) << std::endl;
            exit(-1);
        }
    }

    int Accept(std::string &ip, uint16_t *port)
    {
        sockaddr_in client;
        socklen_t len = sizeof(client);
        int serverSock = accept(_sockfd, (sockaddr *)&client, &len);
        if (serverSock == -1)
        {
            lg(WARNING, "accept fail ! errno:%d %s", errno, strerror(errno));
            return -1;
        }
        *port = ntohs(client.sin_port);
        char ipBuffer[32] = {0};
        ip = inet_ntop(AF_INET, &client.sin_addr, ipBuffer, sizeof(ipBuffer));
        return serverSock;
    }

    bool Connect(const std::string &ip, uint16_t port)
    {
        sockaddr_in client;
        client.sin_family = AF_INET;
        client.sin_addr.s_addr = inet_addr(ip.c_str());
        client.sin_port = htons(port);

        if (connect(_sockfd, (sockaddr *)&client, sizeof(client)) == -1)
        {
            lg(WARNING, "connect fail ! errno:%d %s", errno, strerror(errno));

            return false;
        }
        return true;
    }

    void Close()
    {
        close(_sockfd);
    }

    int getsock()
    {
        return _sockfd;
    }

    void debug()
    {
        std::cout << "debug" << std::endl;
    }

private:
    int _sockfd;
};